raw_bubbledata = myData['layer2id_keywords']
let layer1info = {}//{layer1id:keywords}
result_base64=myData['result_base64']//预加载文件夹下的base64加速绘制词云图
for (let i in myData['layer1info']) {
  layer1info[i] = myData['layer1info'][i][1][2]
}
//次层同一簇的颜色对应一下
id1toid2 = myData['layer1id_layer2id']
//不是很智能后续再改吧 需要先确定第一层几个主题在生成对应数量的颜色
let colors = ['#FFB600', '#886CFF', '#0084FF', '#4CB690', '#58B458', '#6C6C6C', '#F56161', '#FC754C'];
let colorIndex = 0;
let bubbleColors = {};//layer2keywords->color对应
let blockColors = {};//layer1keywords->color对应
for (let key in id1toid2) {
  let values = id1toid2[key];
  for (let value of values) {
    bubbleColors[raw_bubbledata[value][0]] = colors[colorIndex];
  }
  blockColors[layer1info[key]] = colors[colorIndex];
  colorIndex += 1;
}
let transformedData = [];
for (let key in raw_bubbledata) {
  transformedData.push({ name: raw_bubbledata[key][0], amount: raw_bubbledata[key][1] });
}
let format = ['name', 'amount'];
let [maxValue, temp] = [0, []];
transformedData.forEach(item => {
  temp.push(item[format[1]]);
});
maxValue = Math.max.apply(null, temp);
let bubbleData = [];
let basicSize = 70;
let repulsion = 600;
if (transformedData.length >= 5 && transformedData.length < 10) {
  basicSize = 100;
  repulsion = 450;
}
if (transformedData.length >= 10 && transformedData.length < 20) {
  basicSize = 90;
  repulsion = 360;
} else if (transformedData.length >= 20) {
  basicSize = 60;//气泡大小
  repulsion = 170;//气泡间距
}
for (let item of transformedData) {
  curColor = bubbleColors[item["name"]]
  let size = (item[format[1]] * basicSize * 2) / maxValue;
  if (size < basicSize) size = basicSize;
  bubbleData.push({
    "name": item[format[0]],
    "value": item[format[1]],
    "symbolSize": size,
    "draggable": true,
    "itemStyle": {
      "normal": { "color": curColor }
    }
  });
}
// 随机抽样函数
function getRandomSample(array, sampleSize) {
  var sampledArray = [];
  var arrayCopy = array.slice(0); // 创建原数组的副本，避免修改原数组

  for (var i = 0; i < sampleSize; i++) {
    var randomIndex = Math.floor(Math.random() * arrayCopy.length);
    sampledArray.push(arrayCopy.splice(randomIndex, 1)[0]);
  }

  return sampledArray;
}
let successPopup = document.getElementById('success-popup');
//点击事件获得用户点击第一层主题下的所有数据用于后面的绘图
function handleClick (key) {          //key为关键词
  // 在函数开头定义变量来获取弹出框的元素
  var loadingPopup = document.getElementById('loadingPopup');
  // 显示弹出框和加载动画
  loadingPopup.style.display = 'block';

  var clickdata = [];
  var linechartData = {};//用于绘制折线图
  
  for (let i in myData['layer1info']) {
    if (key == myData['layer1info'][i][1][2]) {
      clickdata = myData['layer1info'][i];
      linechartData[key] = myData['linechartinfo'][i]
      break;
    }
  }
  var wordcloudData = ''; // 用于拼接的文本
  var sampledData = clickdata; // 用于存储抽样后的数据
  // 如果clickdata长度大于1500，则进行抽样
  if (clickdata.length > 1500) {
    // 使用随机抽样函数对clickdata进行抽样
    sampledData = getRandomSample(clickdata, 1500);
  }else {
    sampledData = clickdata;
  }
  // 将抽样后的数据进行拼接
  for (var i = 0; i < sampledData.length; i++) {
    wordcloudData += sampledData[i][0];
  }

  fetch('/str2wordfreq', {
    method: 'POST',
    headers: {
      'Content-Type': 'text/plain'
    },
    body: wordcloudData // 直接将wordcloudData作为请求的主体
  })
    .then(response => response.json())
    .then(result => {
      wordcloudData_final = result;
      loadingPopup.style.display = 'none'; // 隐藏弹出框
      //分析按钮弹框
    successPopup.style.display = 'block';
    // 2秒后隐藏分析成功框
    setTimeout(() => {
      successPopup.style.display = 'none';
    }, 2000);
      var clear_button = document.getElementById('dropdown-container');
      clear_button.innerHTML = '';
      box2_wordcloud();//绘制词云
    })
    .catch(error => {
      console.error('Error:', error);
    })
    .finally(() => {
      // 隐藏弹出框
      loadingPopup.style.display = 'none';
    });
  //绘制折线图
  drawLinechart(linechartData);
}
//配置echarts图表
let rectangleID = document.getElementById("rectangle");
let bubbleId = document.getElementById("Bubble");
let bubbleChart = echarts.init(bubbleId);
let rectangleChart = echarts.init(rectangleID);
// 辅助函数：调整颜色的亮度或饱和度
function shadeColor(color, percent) {
  let num = parseInt(color.slice(1), 16);
  let amt = Math.round(2.55 * percent);
  let R = (num >> 16) + amt;
  let G = (num >> 8 & 0x00FF) + amt;
  let B = (num & 0x0000FF) + amt;
  return `#${(0x1000000 | (R < 255 ? (R < 1 ? 0 : R) : 255) << 16 | (G < 255 ? (G < 1 ? 0 : G) : 255) << 8 | (B < 255 ? (B < 1 ? 0 : B) : 255)).toString(16).slice(1)}`;
}
//鼠标移动到长方形块时动态效果放大且变色
let zr = rectangleChart.getZr();
zr.on('mouseover', params => {
  if (params.target) {
    let group = params.target.parent; //获取包含长方形和文字的组
    if (group) {
      let rect = group.children()[0]; //获取长方形
      let rectShape = rect.shape;
      let centerX = rectShape.x + rectShape.width / 2;
      let centerY = rectShape.y + rectShape.height / 2;
      group.attr({
        scale: [1.1, 1.1], //整个组放大
        origin: [centerX, centerY] //设置缩放原点为长方形的中心点
      });
      let originalColor = rect.style.fill;
      let darkerColor = shadeColor(originalColor, -20); //调整颜色的亮度或饱和度，使颜色变深
      rect.attr({
        style: {
          fill: darkerColor //设置鼠标悬停时的颜色，变深的颜色
        }
      });
    }
  }
});
zr.on('mouseout', params => {
  if (params.target) {
    let group = params.target.parent; //获取包含长方形和文字的组
    if (group) {
      group.attr({
        scale: [1, 1], //整个组恢复原大小
        origin: [0, 0] //恢复缩放原点为默认值
      });
      let rect = group.children()[0]; //获取长方形
      let rectId = rect.id;
      rect.attr({
        style: {
          fill: blockColors[rectId] //恢复原本的颜色
        }
      });
    }
  }
});

let bubbleCentral = document.querySelector('.bubble_central');
let bubbleCentralWidth = bubbleCentral.getBoundingClientRect().width;
let rectangleOptions = {
  backgroundColor: '#0c3855',
  animationEasingUpdate: 'bounceIn',
  graphic: Object.keys(blockColors).map((key, index) => {
    let spacing = 40; // 调整长方形块之间的距离
    let blockHeight = 40;
    let textWidth = 290; // 每个长方形块文字的宽度
    return {
      type: 'group',
      onclick: () => handleClick(key), // Set the click event for the entire group
      children: [
        // 长方形块
        {
          type: 'rect',
          id: key,
          shape: {
            x: (bubbleCentralWidth - 330) / 2, // bubble_central的中间
            y: index * (blockHeight + spacing), // Dynamically set the y position based on the index
            width: 330,
            height: blockHeight,
            r: 10 // 添加这一行，将长方形块的四个角变为圆角，数字可以根据你的需求调整
          },
          style: {
            fill: blockColors[key]
          }
        },
        // 添加长方形块的文字
        {
          type: 'text',
          left: (bubbleCentralWidth - 330) / 2 + (330 - textWidth) / 2, // Adjust the position of the text
          top: index * (blockHeight + spacing) + 12, // Adjust the position of the text
          style: {
            text: key,
            fill: '#000', // Set the color of the text
            fontWeight: 'bold', // Set the font weight of the text to bold
            fontSize: 13, // Set the font size of the text
            width: textWidth, // Set the width of the text
            overflow: 'break' // Truncate the text if it exceeds the width
          },
          silent: true // Allow the rectangle to receive click events instead of the text
        }
      ]
    };
  }),
};
let bubbleOptions = {
  backgroundColor: '#0c3855',
  animationEasingUpdate: 'bounceIn',
  series: [{
    type: 'graph',
    layout: 'force',
    force: {
      repulsion: repulsion,
      edgeLength: 10
    },
    roam: false,
    label: {
      normal: {
        show: true,
        fontSize: 10,
        color: '#000',
        fontWeight: 'bold',
        formatter: function(params) {
          let label = params.name;
          let maxLength = 10; // 设置最大长度
          if (label.length > maxLength) {
            if (params.dataType === 'node') {
              // 鼠标移动到气泡上时显示完整文字
              label = params.name;
            } else {
              // 超过最大长度时截断并添加省略号
              label = label.substring(0, maxLength) + '...';
            }
          }
          return label;
        },
        rich: {
          ellipsis: {
            fontSize: 10,
            fontWeight: 'bold',
            color: '#000',
            textBorderColor: '#000',
            textBorderWidth: 1,
            textBorderRadius: 2,
            padding: 2
          }
        }
      }
    },
    data: bubbleData
  }],
  tooltip: {
    formatter: function(params) {
      if (params.dataType === 'node') {
        return '<b style="color:' + params.color + '">' + params.name + '</b>';
      }
    }
  }
};

bubbleChart.setOption(bubbleOptions);
rectangleChart.setOption(rectangleOptions);
